package com.tmt.im.service.helper;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.im.common.enums.CustomizedMsgCode;
import com.tmt.im.common.pojo.ChatSessionMemberPoJo;
import com.tmt.im.common.pojo.SessionMemberKey;
import com.tmt.im.common.yunxin.IYunXinMsgSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.ignite.IgniteCache;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/10/17 19:15
 * @Version 1.0
 **/
@Slf4j
public class SessionNotifyHelper {

    public static void sendChangedNotify(Long currentUserId, Long tid, CustomizedMsgCode type, Long changedMemberId,
                                         IgniteCache<SessionMemberKey, ChatSessionMemberPoJo> sessionMemberCache,
                                         IYunXinMsgSender iYunXinMsgSender) {
        String sql = MessageFormat.format("select * from {0} where checkStatus = 1 and sessionId = ?",
                ChatSessionMemberPoJo.CACHE_NAME);
        List<ChatSessionMemberPoJo> memberPoJos = IgniteQueryHelper.findAllBy(sql, new Object[]{tid},
                ChatSessionMemberPoJo.class, sessionMemberCache);
        List<Long> memberIds = memberPoJos.stream().map(ChatSessionMemberPoJo::getMemberId).toList();
        if (CollectionUtils.isEmpty(memberIds)) {
            return;
        }

        JSONObject json = new JSONObject();
        json.put("type", type.getType());
        json.put("msg", type.getMsg());
        if (changedMemberId != null) {
            json.put("memberId", changedMemberId);
        }
        StringBuilder error = new StringBuilder();
        for (Long memberId : memberIds) {
            error.setLength(0);
            if (!iYunXinMsgSender.sendCustomizedMsg(currentUserId, memberId, json, error)) {
                log.error("-----发送{}通知失败----{}", type.getMsg(), error);
            }
        }
    }
}
